package xiaojian.toolkit.netty.handler.codec.http.reactor;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import org.springframework.util.Assert;

import xiaojian.toolkit.netty.handler.codec.http.request.HttpRequestExt;
import xiaojian.toolkit.netty.handler.codec.http.response.HttpResponseBuilder;
import xiaojian.toolkit.netty.handler.codec.http.response.HttpResponseSender;
import xiaojian.toolkit.netty.util.NettyConstants;

/**
 * @author hp
 * 
 */
public class SendbackResponseReactor implements HttpReactor {

	private HttpReactor nextReactor = null;
	private HttpResponseBuilder responseBuilder;
	private HttpResponseSender responseSender;

	public HttpResponseBuilder getResponseBuilder() {
		return responseBuilder;
	}

	public void setResponseBuilder(HttpResponseBuilder responseBuilder) {
		this.responseBuilder = responseBuilder;
	}

	public HttpResponseSender getResponseSender() {
		return responseSender;
	}

	public void setResponseSender(HttpResponseSender responseSender) {
		this.responseSender = responseSender;
	}

	public HttpReactor getNextReactor() {
		return nextReactor;
	}

	public void setNextReactor(HttpReactor nextReactor) {
		this.nextReactor = nextReactor;
	}

	@Override
	public void onHttpRequest(FullHttpRequest request) {
		Assert.isInstanceOf(HttpRequestExt.class, request,
				"request must be type of HttpRequestExt");
		HttpRequestExt requestExt = (HttpRequestExt) request;
		HttpResponse resp = responseBuilder.build("ok");
		String uuid = request.headers().get(NettyConstants.HEADER_UUID);
		if (uuid != null) {
			resp.headers().set(NettyConstants.HEADER_UUID, uuid);
		}
		responseSender.sendResponse((Channel) requestExt
				.getProperty(NettyConstants.PROPERTY_CHANNEL), resp);
		if (null != this.nextReactor) {
			nextReactor.onHttpRequest(request);
		}
	}

}
